#include "audiothread.h"

#include <QDebug>
#include <QFile>
#include <QDateTime>

#include "ffmpegs.h"

extern "C" {
// 设备
#include <libavdevice/avdevice.h>
// 格式
#include <libavformat/avformat.h>
// 工具
#include <libavutil/avutil.h>
}

#ifdef Q_OS_WIN

#else
    #define FMT_NAME "avfoundation"
    #define DEVICE_NAME ":0"
    #define FILEPATH "/Users/os/Desktop/"
#endif

AudioThread::AudioThread(QObject *parent) : QThread(parent) {
    connect(this, &AudioThread::finished, this, &AudioThread::deleteLater);
}

AudioThread::~AudioThread() {
    disconnect();
    requestInterruption();
    quit();
    wait();

    qDebug() << this << "析构了";
}

void AudioThread::run() {

    qDebug() << this << "开始采集....";

    AVInputFormat *fmt = av_find_input_format(FMT_NAME);
    if (!fmt) {
        qDebug() << "获取输入格式对象失败" << FMT_NAME;
        return;
    }

    AVFormatContext *ctx = nullptr;
    int ret = avformat_open_input(&ctx, DEVICE_NAME, fmt, nullptr);
    if (ret < 0) {
        char errbuf[1024];
        av_strerror(ret, errbuf, sizeof (errbuf));
        qDebug() << "打开设备失败" << errbuf;
        return;
    }

    // 文件名
    QString filename = FILEPATH;
    filename += QDateTime::currentDateTime().toString("MM_dd_HH_mm_ss");
    filename += ".wav";
    QFile file(filename);

    if (!file.open(QFile::WriteOnly)) {
        qDebug() << "文件打开失败" << filename;
        // 关闭设备
        avformat_close_input(&ctx);
        return;
    }

    AVStream *stream = ctx->streams[0];
    AVCodecParameters *params = stream->codecpar;

    WAVHeader header;
    header.sampleRate = params->sample_rate;
    header.bitsPerSample = av_get_bits_per_sample(params->codec_id);
    if (params->codec_id >= AV_CODEC_ID_PCM_F32BE) {
        header.audioFormat = AUDIO_FORMAT_FLOAT;
    }
    header.blockAlign = header.bitsPerSample * header.numChannels >> 3;
    header.byteRate = header.sampleRate * header.blockAlign;

    file.write((char *)&header, sizeof (WAVHeader));

    AVPacket pkt;
    while (!isInterruptionRequested()) {
        ret = av_read_frame(ctx, &pkt);

        if (ret == 0) {
            file.write((char *)pkt.data, pkt.size);

            header.dataChunkDataSize += pkt.size;
            unsigned long long ms = 1000 * header.dataChunkDataSize / header.byteRate;
            emit timeChanged(ms);
        } else if (ret == AVERROR(EAGAIN)) {
            continue;
        } else {
            char errbuf[1024];
            av_strerror(ret, errbuf, sizeof (errbuf));
            qDebug() << "av_read_frame error" << errbuf << ret;
            break;
        }
    }

    file.seek(sizeof (WAVHeader) - sizeof (header.dataChunkDataSize));
    file.write((char *)&header.dataChunkDataSize, sizeof (header.dataChunkDataSize));

    header.riffChunkDataSize = file.size() - sizeof (header.riffChunkId) - sizeof (header.riffChunkDataSize);
    file.seek(sizeof (header.riffChunkId));
    file.write((char *)&header.riffChunkDataSize, sizeof (header.riffChunkDataSize));

    file.close();

    avformat_close_input(&ctx);

    qDebug() << this << "正常结束....";
}

